package control.table
{
	import control.panel.PanelControl;
	
	import events.MailEvent;
	
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.events.Event;
	
	import global.GameState;
	import global.Resource;
	
	import utils.DisplayTool;
	import utils.animate.AlphaMoveTween;
	
	import view.panel.mail.MailPanel;

	public class MailControl extends PanelControl
	{
		
		private var tweens:Array;
			
		public function MailControl() 
		{
			initPanel();
			initTweens();
			initListener();
		}
		
		private function initPanel():void
		{
			_view.mailPanel = new MailPanel(this);
		}
		
		public function open():void
		{
			_view.mailPanel.open();
		}
		
		public function mailResult():void
		{
			_model.mailModel.sendMailResult();
		}
		
		private function initTweens():void
		{
			tweens = [];

			var tween:AlphaMoveTween
			for (var i:int=0; i<6; i++)
			{
				tween = new AlphaMoveTween();
				tween.duration = 1;
				tween.addEventListener(Event.COMPLETE,onTweenComplete);
				tweens.push(tween);
			}
			 
		}
		
		private function onTweenComplete(event:Event):void
		{
			var tween:AlphaMoveTween = event.target as AlphaMoveTween;
			clearTween(tween);
		}
		
		private function clearTween(tween:AlphaMoveTween):void
		{
			if (tween)
			{
				if (tween.target)
				{
					(tween.target as Bitmap).bitmapData = null;
					DisplayTool.removeChild(tween.target.parent,tween.target);
				}
				
			}
		}
		
		private function initListener():void
		{
			_model.mailModel.addEventListener(MailEvent.MAIL_ARRIVE,onMailArrive);
			_model.mailModel.addEventListener(MailEvent.MAIL_ANIMATION,onMailAnimation);
		}
		
		private function onMailAnimation(event:MailEvent):void
		{
			var fromSitId:int = event.fromId;
			var toSitId:int = event.toId;
			
			var tween:AlphaMoveTween = tweens[fromSitId];
			tween.stop();
			clearTween(tween);
			var fx:int = GameState.sitButXYS[fromSitId][0];
			var fy:int = GameState.sitButXYS[fromSitId][1];
			var tx:int = GameState.sitButXYS[toSitId][0];
			var ty:int = GameState.sitButXYS[toSitId][1];
			var target:DisplayObject = Resource.getImg("face_flyMail");
			tween.setTarget(target,fx,fy,tx,ty);
			tween.start();
			
			_view.tableLayer.addEmote(target);
		}
		
		private function onMailArrive(event:MailEvent):void
		{
			_view.tableLayer.showHideMailBut(true);
			
			if (_view.mailPanel.parent)
			{
				mailButClick();
			}
		}
		
		public function mailButClick():void
		{
			_view.tableLayer.showHideMailBut(false);
			open();
			_view.mailPanel.clear();
			var datas:Array = _model.mailModel.mailDatas;
			_view.mailPanel.update(datas);
			
		}
		
		public function clear():void
		{
			for each(var tween:AlphaMoveTween in tweens)
			{
				clearTween(tween);
			}
		}
		
	}
}